package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.CollectionManager;
import cn.wolfcode.crm.domain.FormalStudent;
import cn.wolfcode.crm.exception.ClearException;
import cn.wolfcode.crm.exception.LessException;
import cn.wolfcode.crm.mapper.CollectionManagerMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.ICollectionManagerService;
import cn.wolfcode.crm.service.IFormalStudentService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;

@Service
public class CollectionManagerServiceImpl implements ICollectionManagerService {
    @Autowired
    private CollectionManagerMapper collectionManager;
    @Autowired
    private IFormalStudentService formalStudentService;


    public void insert(CollectionManager record) {
        collectionManager.insert(record);
    }

    public void updateByPrimaryKey(CollectionManager record) {
        collectionManager.updateByPrimaryKey(record);
    }

    public PageResult query(QueryObject qo) {
        int total = collectionManager.query4Count(qo);
        if (total > 0) {
            return new PageResult(total, collectionManager.query4List(qo));
        }
        return new PageResult(total, Collections.EMPTY_LIST);
    }

    public void audit(Long id, BigDecimal amount , Long formalStudentId) {
        if(amount.compareTo(BigDecimal.ZERO) <= 0){
            throw new LessException("请输入正确的收款金额");
        }
        FormalStudent formalStudent = formalStudentService.selectById(formalStudentId);
        if(formalStudent.getDebt().compareTo(BigDecimal.ZERO) == 0){
            throw new ClearException("欠款已还清,无需审核");
        }
        Long auditorId = UserContext.getCurrentUser().getId();
        collectionManager.audit(id,auditorId);
        formalStudentService.audit(formalStudentId,amount);

    }

}
